from django.shortcuts import render, redirect
from app01 import models
from app01.utils.pagination import Pagination
from app01.utils.form import PrettyEditModelForm, PrettyModelForm, UserModelFrom

def user_list(request):
    """用户管理"""

    # 获取数据库用户信息
    queryset = models.UserInfo.objects.all()
    """
    for obj in queryset:
        print(
            obj.id,
            obj.name,
            obj.password,
            obj.age,
            obj.account,
            obj.create_time.strftime("%Y-%m-%d"),   # 转换为字符串并去年月日
            obj.get_gender_display(),   # 前面数据库封装好了的1代表男 2代表女
            obj.depart.title    # 跨表拿到对应的数据
        )
    """
    page_object = Pagination(request, queryset, page_size=2)
    context = {
        'queryset': page_object.page_queryset,
        'page_string': page_object.html(),

    }
    return render(request, 'user_list.html', context)


def user_add(request):
    # 判断是什么请求 get
    if request.method == "GET":
        context = {
            # 拿到在到html中输出
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)
    # 否则是post请求
    # 拿到用户输入post的数据
    name = request.POST.get('name')
    password = request.POST.get('password')
    age = request.POST.get('age')
    account = request.POST.get('account')
    create_time = request.POST.get('create_time')
    gender = request.POST.get('gender')
    depart_id = request.POST.get('depart_id')

    # 保存到数据库
    models.UserInfo.objects.create(
        name=name,
        password=password,
        age=age,
        account=account,
        create_time=create_time,
        gender=gender,
        depart_id=depart_id
    )
    # 重定向用户列表
    return redirect('/user/list')


# +++++++++++++++++++++++++++++++ 基于ModelFrom 实列 +++++++++++++++++++++++++++++++


def user_model_from_add(request):
    """添加用户 基于ModelFrom"""
    if request.method == "GET":
        form = UserModelFrom()
        return render(request, 'user_model_from_add.html', {'form': form})

    # POST 提交
    # request.POST用户提交的所有数据给到UserModelFrom
    # 在UserModelFrom会去fields取到每一个字段后
    form = UserModelFrom(data=request.POST)
    # 拿到字段后会对其逐一校验
    if form.is_valid():
        # 如果数据检验正确 保存到数据库
        # {'name': '阿猴鸡', 'password': '14564', 'age': 1, 'account': Decimal('244156'), 'create_time': datetime.datetime(2013, 12, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'gender': 1, 'depart': <Department: 企划部的>}
        # # 常规保存法
        # cleaned_data = form.cleaned_data  # 校验成功得到的数据
        # models.UserInfo.objects.create(name=cleaned_data['name'])
        form.save()  # modelform提供的保存方法
        return redirect('/user/list')  # 保存成功重定向回用户列表页面
    else:
        # 检验失败 在页面显示错误信息
        # print(form.errors)  # 校验失败的到所有的错误信息
        return render(request, 'user_model_from_add.html', {'form': form})


def user_edit(request, nid):
    """编辑用户"""

    row_object = models.UserInfo.objects.filter(id=nid).first()

    if request.method == 'GET':
        # 根据id去数据库获取要编辑的数据(对象)
        # row_object = models.UserInfo.objects.filter(id=nid).first()
        # instance=row_object 加上这个modelform会把默认值显示在输入框
        form = UserModelFrom(instance=row_object)
        return render(request, 'user_edit.html', {"form": form})

    # post
    # row_object = models.UserInfo.objects.filter(id=nid).first() # 拿到对应的行 对象
    form = UserModelFrom(data=request.POST, instance=row_object)  # instance=rew_object 没有就是添加，写了就是更新
    if form.is_valid():
        # 默认保存的是用户输入的数据
        # 如果有些不是用户输入的数据，也要保存到数据库 【model = models.UserInfo 规定的表中
        # form.instance.数据表字段名 = 某个想要保存的数据
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')